#!/bin/bash

# ----------------------------------------------------------------------
# Filename:   dhcp_service.sh
# Version:    1.0
# Date:       2013/09/22
# Author:     huijing.hei
# Email:      huijing.hei@cs2c.com.cn
# Summary:    02系统基本功能-04网络服务-07DHCP-01服务控制和状态查询
# Notes:       ***
# Copyright:    China Standard Software Co., Ltd.
# History：     
#             Version 1.0, 2013/09/22
#             - setup dhcpd.conf, start and stop dhcpd service.
# ----------------------------------------------------------------------
##! @TODO:  update dhcpd.conf
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function do_setup()
{
    trap do_cleanup INT EXIT
    serv=dhcpd

    # get local ip
    local LOCAL_IP=`ifconfig  | grep 'inet ' | grep -m 1 -v '127.0.0.1'  | awk '{print $2}' | tr -d "addr:"`

    # get network IP
    local NET_ID=`echo ${LOCAL_IP} | awk 'BEGIN{OFS=FS="."}{print $1,$2,$3}'`

    DHCP_CONF="/etc/dhcp/dhcpd.conf"

    if [ -r ${DHCP_CONF} ]
    then
        mv ${DHCP_CONF} ${DHCP_CONF}.bak
        EchoResult "backup ${DHCP_CONF}"
    else
        echo "${DHCP_CONF} not exists, pls check"
        exit 1
    fi

    # setup dhcpd.conf
    if [ "x" != "${NET_ID}x" ];then
    cat > ${DHCP_CONF} <<-EOF
subnet ${NET_ID}.0 netmask 255.255.255.0{
range ${NET_ID}.101 ${NET_ID}.110;
default-lease-time 6000;
max-lease-time 7200;
option time-offset -3600;
}
EOF
    else
        echo "net id is null, pls check"
        exit 1
    fi


}

##! @TODO:  start and stop dhcpd service.
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure

function do_test()
{
    echo "Test: start, stop dhcpd service."    

    # if dhcpd started, then stop, or start
    status_daemon ${serv}  && stop_daemon ${serv} || start_daemon ${serv}
    EchoResult "${serv} start&stop"

    # dhcpd restart
    restart_daemon ${serv}
    sleep 3
    netstat -nutlp | grep ${serv}
    EchoResult "${serv} restart"

    #
}

##! @TODO:  cleanup tmp files, back up vsftpd.conf and restart ftp services.
##! @AUTHOR: huijing.hei
##! @VERSION: 1.0 
##! @OUT: 0 => success; 1 => failure
function do_cleanup()
{
    stop_daemon ${serv}
    [ -f ${DHCP_CONF}.bak ] && mv -f ${DHCP_CONF}.bak ${DHCP_CONF}

}

if [ -z "$SFROOT" ]
then
    echo "SFROOT is null, pls check"
    exit 1
else
    CMDLIB=${SFROOT}/testcases/Network_Service
fi


. ${SFROOT}/lib/Echo.sh
. ${CMDLIB}/lib/Net.sh


# main
do_setup
do_test || { echo "testcase failed."; exit 1; }
exit 0
